package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/generic/utils"
)

type MyResource struct {
	// 资源属性
}

func CreateMyResource() (MyResource, error) {
	// 实现资源创建逻辑
	fmt.Println("Create Resource")
	return MyResource{}, nil
}

func DestroyMyResource(r MyResource) error {
	// 实现资源销毁逻辑
	fmt.Println("Destroy Resource")
	return nil
}

func main() {
	lr := utils.NewLimitedResource(
		10,
		CreateMyResource,
		DestroyMyResource,
		5*time.Second,
	)

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	resource, err := lr.Borrow(ctx)
	if err != nil {
		log.Fatal(err)
	}

	// 模拟自动destroy
	go func() {
		rs, err := lr.Borrow(ctx)
		if err != nil {
			log.Fatal(err)
		}
		time.Sleep(7 * time.Second)
		if err := lr.Return(rs); err != nil {
			log.Fatal(err)
		}
	}()

	if err := lr.Return(resource); err != nil {
		log.Fatal(err)
	}
	time.Sleep(10 * time.Second)
	if err := lr.Shutdown(); err != nil {
		log.Fatal(err)
	}
}
